/*========================================================================
#   FileName: main.c
#     Author: lwd
#      Email: lwd_xinghuo@126.com
#   HomePage: 
# LastChange: 2013-05-16 20:12:54
========================================================================*/
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/msg.h>
#include <pthread.h>
#include "public.h"
#include "Process.h"
#include "control.h"
#include "prosync.h"
#include "manage.h"
#include "socketfunc.h"
#include "config.h"

int main(int argc, char* argv[])
{
	/* 
	 * 系统初始化
	 * 初始化PV操作
	 * 初始化父进程与子进程之间到同步PV（pro_P \pro_V）
	 * 初始化进程队列
	 * 初始化服务列表（读取配置文件./config/config.ini）
	 *
	 */
	
	if(init_P_V())
	{
		perror("init_P_V error!\n");
		exit(EXIT_FAILURE);
	}
	
	//init process sync ( P()/ V())
	if(init_pro_sync())
	{
		perror("init_pro_sync error!\n");
		exit(EXIT_FAILURE);
	}
	
	//init process-list
	if(init_PQueue())
	{
		perror("init process-list error!\n");
		exit(EXIT_FAILURE);
	}
	
	if(init_msg())
	{
		perror("init msg error!\n");
		exit(EXIT_FAILURE);
	}
	
	if(init_service_list())
	{
		printf("ERROR:init_service_list error!\n");
		exit(EXIT_FAILURE);
	}
	/*
	 * 创建两个线程，
	 * 线程1：进程调度线程
	 * 线程2：socket线程（服务器线程），等待客户端的请求消息
	 *        并根据请求做出相应到操作
	 *
	 */
	int ret;
	pthread_t crtpro, magpro;
#if 1
	ret = pthread_create(&magpro, NULL, manage, NULL);
	if(ret != 0)
	{
		printf("ERROR:create pthread! func:%s line:%d", \
				__func__, __LINE__);
		exit(EXIT_FAILURE);
	}
#endif
#if 0 
	ret = pthread_create(&crtpro, NULL, createProcesses, NULL);
	if(ret != 0)
	{
		printf("ERROR:create pthread! func:%s line:%d", \
				__func__, __LINE__);
		exit(EXIT_FAILURE);
	}
#endif
#if 1
	ret = pthread_create(&crtpro, NULL, serverStartup, NULL);
	if(ret != 0)
	{
		printf("ERROR:startup server error!\n");
		exit(EXIT_FAILURE);
}
#endif
	/*  
	 * 等待上述两个主线程结束
	 *  */
	/*
	//waitting for all the pthread finished
	if(!pthread_join(crtpro, NULL))
	{
		printf("thread crtpro finished!\n");
	}
	*/
	if(!pthread_join(magpro, NULL))
	{
		printf("thread magpro finished!\n");
	}
	
	return 0;
}

